﻿using System.Drawing;
using System.Windows.Forms;
using NGridDrawer.Partitions;
using NGridDrawer.Report;
using NGridDrawer.Report.Layout;

namespace NGridDrawer.Draw
{
    /// <LastUpdate author="Blaise Braye" Date="06/08/2008 13:39"/>
    ///<summary>
    /// This class prints tooltips contained in <see cref="DataGridView"/> objects below 
    /// a <see cref="DataGridViewAbstractDrawer"/> object
    ///</summary>
    public class DataGridViewAnnotatedDrawer : GridAnnotatedDrawer
    {
        ///<summary>
        ///    <para>Initializes an instance of the <see cref="DataGridViewAnnotatedDrawer"/> class.</para>
        ///</summary>
        ///<param name="drawer">drawer to encapsulate (see global remark about decorator pattern)</param>
        public DataGridViewAnnotatedDrawer(DataGridViewAbstractDrawer drawer)
            : base(drawer)
        {
            Drawer = drawer;
            ElementDrawing += dataGridViewAnnotatedDrawer_ElementDrawing;
            RowRequestedBlock += dataGridViewAnnotatedDrawer_RowRequestedBlock;
        }

        ///<summary>Get/Set Drawer property
        ///</summary>
        public DataGridViewAbstractDrawer Drawer { get; set; }


        private void dataGridViewAnnotatedDrawer_RowRequestedBlock(object sender, RowRequestedBlockEventArgs e)
        {
            e.AttachedToRow = buildCommentBlock(e);
        }


        private IBlock buildCommentBlock(RowRequestedBlockEventArgs e)
        {
            PartitionColumn pcol = e.PartitionColumn;

            var container = new BlockLayoutVertical();

            for (int colKey = pcol.FirstColumn; colKey <= pcol.LastColumn; colKey++)
            {
                DataGridViewCell cell = Drawer.Mapping.Cell(e.RowIndex, colKey);

                if (!string.IsNullOrEmpty(cell.ToolTipText))
                    container.AddBlock(new BlockComment(cell.ToolTipText, e.RowIndex, colKey));
            }

            return container.IsEmpty ? null : container;
        }

        private static void dataGridViewAnnotatedDrawer_ElementDrawing(object sender, ElementDrawnEventArgs e)
        {
            var cell = sender as DataGridViewCell;

            if (cell != null)
            {
                if (!string.IsNullOrEmpty(cell.ToolTipText))
                {
                    float top = e.Bounds.Y;
                    float right = e.Bounds.Right;

                    PointF[] mypoints =
                        {
                            new PointF(right - 5, top),
                            new PointF(right, top),
                            new PointF(right, top + 5)
                        };
                    e.Graphic.FillPolygon(new SolidBrush(Color.Red), mypoints);
                }
            }
        }
    }
}